import collections

from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from import_export import resources
from import_export.admin import ImportExportActionModelAdmin
from import_export.fields import Field

from app.admin import SimpleModelAdmin
from sales.models import *


class OrderItemInline(admin.TabularInline):
    model = OrderItem
    extra = 0
    fields = ['product_sales', 'amount', 'price_initial', 'price_payed', 'vip_level']
    autocomplete_fields = ['product_sales']


class ProductSalesResource(resources.ModelResource):
    id = Field(attribute='id', column_name='id')
    order_number = Field(attribute='order_number', column_name='订单号', readonly=True)
    logistics_number = Field(attribute='logistics_number', column_name='物流单号')
    items = Field(column_name='明细', readonly=True)
    user__id = Field(attribute='user__id', column_name='用户ID', readonly=True)
    address__name = Field(attribute='address__name', column_name='收件人', readonly=True)
    address__mobile = Field(attribute='address__mobile', column_name='手机号', readonly=True)
    address__address = Field(attribute='address__address', column_name='城市', readonly=True)
    address__area = Field(attribute='address__area', column_name='地址', readonly=True)
    customer_notes = Field(attribute='customer_notes', column_name='客户备注')
    price_initial = Field(attribute='price_initial', column_name='订单原价', readonly=True)
    price_payed = Field(attribute='price_payed', column_name='支付金额', readonly=True)
    is_payed = Field(attribute='is_payed', column_name='已支付')
    is_send = Field(attribute='is_send', column_name='已发货')
    order_state = Field(attribute='order_state', column_name='订单状态', readonly=True)
    pay_record = Field(attribute='pay_record', column_name='支付记录', readonly=True)
    notes = Field(attribute='notes', column_name='后台备注')
    datetime_created = Field(attribute='datetime_created', column_name='下单时间', readonly=True)

    def get_queryset(self):
        return ProductSalesOrder.objects.filter(is_show=True).order_by('order_number')

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        res = []
        for row in dataset.dict:
            tmp = collections.OrderedDict()
            for item in row:
                if item in {'id', 'logistics_number', 'notes'}:
                    tmp[item] = row[item]
            res.append(tmp)
        dataset.dict = res
        return dataset

    def dehydrate_items(self, obj):
        order_items = OrderItem.objects.filter(
            product_sales_order_id=obj.pk
        ).values(
            'product_sales_id',
            'product_sales__product_batch__product_info__name_cn',
            'product_sales__product_batch__product_info__bottle_size',
            'amount'
        )
        res = list()
        for order_item in order_items:
            res.append('{}.{}({})*{}'.format(
                order_item['product_sales_id'],
                order_item['product_sales__product_batch__product_info__name_cn'],
                order_item['product_sales__product_batch__product_info__bottle_size'],
                order_item['amount'],
            ))
        res_str = ''
        if res:
            res_str = '\n\r'.join(res)
        return res_str

    def dehydrate_order_state(self, obj):
        res_str = dict(order_state_choices).get(obj.order_state)
        return res_str

    class Meta:
        model = ProductSalesOrder
        skip_unchanged = True
        report_skipped = True
        fields = (
            'id',
            'order_number',
            'logistics_number',
            'items',
            'user__id',
            'address__name',
            'address__mobile',
            'address__address',
            'address__area',
            'customer_notes',
            'price_initial',
            'price_payed',
            'is_payed',
            'is_send',
            'order_state',
            'pay_record',
            'notes',
            'datetime_created'
        )
        export_order = fields
        widgets = {
            'datetime_created': {'format': '%Y-%m-%d'},
        }


@admin.register(ProductSalesOrder)
class ProductSalesOrderAdmin(ImportExportActionModelAdmin):

    def items(self, obj):
        res = list()
        for row in obj.order_items:
            res.append('{}.{}({}ml)*{}'.format(
                row.get('product_sales', {}).get('id', 0),
                row.get('product_sales', {}).get('product_batch', {}).get('product_info', {}).get('name_cn', ''),
                row.get('product_sales', {}).get('product_batch', {}).get('product_info', {}).get('bottle_size', ''),
                row.get('amount', 0),
            ))
        return ';'.join(res)

    view_on_site = False
    readonly_fields = ['datetime_created', 'datetime_updated']
    list_display = [
        'pk', 'order_number', 'logistics_number', 'logistics_push', 'items',
        'user', 'address', 'customer_notes', 'price_initial', 'price_payed',
        'is_payed', 'is_send', 'is_show', 'order_state', 'notes'
    ]
    list_filter = ['is_payed', 'is_send', 'order_state', 'is_show', 'user', 'datetime_created']
    list_display_links = ['pk', 'order_number']
    search_fields = ['order_number', 'user__id', 'address__id', 'user__mobile', 'address__mobile']
    fieldsets = (
        (_('订单状态'), {'fields': ('logistics_number', 'is_payed', 'is_send', 'is_show', 'order_state')}),
        (_('基础信息'), {'fields': ('order_number', 'user', 'address', 'customer_notes')}),
        (_('订单金额'), {'fields': ('price_initial', 'price_payed')}),
        (_('备注'), {'fields': ('notes', 'datetime_created', 'datetime_updated'), 'classes': ('collapse',)}),
    )
    save_on_top = True
    autocomplete_fields = ['user', 'address']

    list_editable = ['is_payed', 'is_send', 'is_show']

    inlines = [OrderItemInline]

    resource_class = ProductSalesResource


@admin.register(OrderItem)
class OrderItemAdmin(SimpleModelAdmin):
    list_display = [
        'pk', 'product_sales_order', 'product_sales', 'amount', 'vip_level', 'price_initial', 'price_payed']
    list_display_links = ['pk', 'product_sales_order']
    autocomplete_fields = ['product_sales_order', 'product_sales', 'vip_level']
    search_fields = ['product_sales_order__order_number', 'product_sales__product_batch__product_info__name_cn']
    list_filter = ['vip_level', 'product_sales_order__user']
